package cn.ailearn.module.controller;

import cn.ailearn.module.pojo.dto.AccountDto;
import cn.ailearn.security.details.MySysUserDetails;
import cn.ailearn.utils.JWTUtils;
import cn.ailearn.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static cn.ailearn.constant.RedisConstants.RedisKey.TOKEN_USERINFO_KEY;

/**
 * @ClassName HelloController
 * @Description TODO
 * @Author WDEMO
 * @Date 2025/10/22 16:37
 */
@RestController
public class HelloController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtils redisUtils;


    @PostMapping("/login")
    public String Hello(@RequestBody AccountDto accountDto) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(accountDto.getUsername(), accountDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        Object principal = authenticate.getPrincipal();
        MySysUserDetails loginDto = null;
        if (principal instanceof MySysUserDetails) {
            loginDto = (MySysUserDetails) principal;
        }
        if (Objects.isNull(loginDto)) {
            throw new RuntimeException("登录失败");
        }

        //生成token
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("user_id", "1232");
        String token = JWTUtils.createToken(claims);

        //添加进缓存中
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put(loginDto.getUsername(), token);
        redisUtils.setCacheMap(TOKEN_USERINFO_KEY, dataMap);
        redisUtils.expire(TOKEN_USERINFO_KEY, 30, TimeUnit.MINUTES);//有效期为30分钟

        //返回token
        return token;
    }

}
